import { GroupProps } from '@react-three/fiber';
import React, { useEffect, useState } from 'react';
import * as THREE from 'three';

const petalColors = [0xf25346, 0xedeb27, 0x68c3c0];

const Flower = (props: GroupProps) => {
  const [petals, setPetals] = useState<React.ReactNode[]>([]);

  useEffect(() => {
    const material = new THREE.MeshBasicMaterial({
      color: petalColors[Math.floor(Math.random() * 3)],
    });
    const geometry = new THREE.BoxGeometry(15, 20, 5, 1, 1, 1);
    const positions = geometry.getAttribute('position');
    positions.setY(4, positions.getY(4) - 4);
    positions.setY(8, positions.getY(8) - 4);
    positions.setY(21, positions.getY(21) - 4);

    positions.setY(5, positions.getY(5) - 4);
    positions.setY(10, positions.getY(10) - 4);
    positions.setY(16, positions.getY(16) - 4);

    positions.setY(6, positions.getY(6) + 4);
    positions.setY(14, positions.getY(14) + 4);
    positions.setY(23, positions.getY(23) + 4);

    positions.setY(7, positions.getY(7) + 4);
    positions.setY(12, positions.getY(12) + 4);
    positions.setY(18, positions.getY(18) + 4);

    geometry.translate(12.5, 0, 3);

    const petals: React.ReactNode[] = [];
    for (let index = 0; index < 4; index++) {
      petals.push(
        <mesh
          key={index}
          geometry={geometry}
          material={material}
          castShadow
          receiveShadow
          rotation-z={index * Math.PI * 0.5}
        />,
      );
    }
    setPetals(petals);
  }, []);

  return (
    <group {...props}>
      <mesh receiveShadow castShadow>
        <boxGeometry args={[5, 50, 5, 1, 1, 1]} />
        <meshPhongMaterial color={0x458248} flatShading />
      </mesh>
      <mesh receiveShadow castShadow position={[0, 25, 3]}>
        <boxGeometry args={[10, 10, 10, 1, 1, 1]} />
        <meshPhongMaterial color={0xedeb27} flatShading />
        {petals}
      </mesh>
    </group>
  );
};

export default Flower;
